package com.pro.framework.json;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.pro.framework.api.enums.IEnumInt;
import lombok.SneakyThrows;

/**
 * json字符串中的值 和 枚举值 互相转换的实现类
 * @param <T>
 */
public class EnumDeserializer<T extends Enum<T> & IEnumInt> extends JsonDeserializer<T> {

    private final Class<T> enumClass;

    public EnumDeserializer(Class<T> enumClass) {
        this.enumClass = enumClass;
    }

    @Override
    @SneakyThrows
    public T deserialize(JsonParser p, DeserializationContext ctxt) {
        //noinspection unchecked
        return (T) enumClass.getEnumConstants()[0].fromValue(p.getIntValue());
    }
}
